package com.example.crm.service.impl;

import com.example.crm.mapper.CustomerMapper;
import com.example.crm.pojo.Customer;
import com.example.crm.pojo.CustomerExample;
import com.example.crm.service.ICustomerService;
import lombok.Setter;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@Setter
public class CustomerServiceImpl implements ICustomerService {

    /*SqlSessionFactory sqlSessionFactory;
    SqlSession sqlSession;
    CustomerMapper customerMapper;
    //代码块在创建类时就会执行，在构造方法之后
    {
        // 1. 创建SqlSessionFactoryBuilder对象
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder=new SqlSessionFactoryBuilder();
        // 2. 加载SqlMapConfig.xml配置文件
        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 3. 创建SqlSessionFactory对象
        sqlSessionFactory=sqlSessionFactoryBuilder.build(inputStream);
        // 4. 创建SqlSession对象
        sqlSession = sqlSessionFactory.openSession();
        // 5. 执行SqlSession对象执行查询，获取结果User
        // 第一个参数是User.xml的statement的id，第二个参数是执行sql需要的参数；
        customerMapper = sqlSession.getMapper(CustomerMapper.class);
    }*/

    //@Setter相当于下面
    /*public void setCustomerMapper(CustomerMapper customerMapper) {
        this.customerMapper = customerMapper;
    }*/

    /*@Autowired*/
    CustomerMapper customerMapper;

    public List<Customer> findAll() {
        return customerMapper.selectByExample(null);
    }

    @Override
    public List<Customer> findUser(Customer customer) {
        return customerMapper.selectByExample2(customer);
    }

    @Override
    public int saveUser(Customer customer) {
        int i = customerMapper.insert(customer);
        /*sqlSession.commit();
        sqlSession.close();*/
        return i;
    }

    @Override
    public int updateUser(Customer customer) {
        int i=customerMapper.updateByPrimaryKey(customer);
        /*sqlSession.commit();
        sqlSession.close();*/
        return i;
    }

    @Override
    public int deleteUser(long id) {
        int i = customerMapper.deleteByPrimaryKey(id);
        /*sqlSession.commit();
        sqlSession.close();*/
        return i;
    }

}
